package com.elecbook.media.api.controller;

import com.elecbook.base.result.Result;
import com.elecbook.media.api.config.data.MongodbConfig;
import com.elecbook.media.api.service.data.MongoDbService;
import com.elecbook.media.model.po.UploadFile;
import com.elecbook.media.model.po.UploadImage;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/file")
public class UploadFileController {

    private final MongoTemplate mongoTemplate;

    private final MongodbConfig mongodbConfig;

    private final MongoDbService mongoDbService;

    /**
     * 图片上传
     */
    @PostMapping("/uploadImage")
    public Result<String> uploadImage(@RequestParam(value = "image") MultipartFile file) {

        if (file.isEmpty())
            return Result.error("请选择一张图片");

        Result<String> result;
        try {
            // 转换为上传文件的实体
            UploadImage uploadImage = mongoDbService.getUploadImageEntity(file);
            // 通过 mongoTemplate 保存后，会把数据库自动生成的主键赋值到这个对象上
            UploadImage saveImage = mongoDbService.uploadImage(uploadImage);
            // 构造好这个图片的请求地址返回给前端，我们后面实现这个请求
//            String url = "http://localhost:8080/file/image/" + savedFile.getId();
            String url = mongodbConfig.publicHost + MongodbConfig.IMAGE + saveImage.getId();
            result = Result.success(url);
        } catch (IOException e) {
            log.error("图片上传失败", e);
            result = Result.error("图片上传失败");
        }
        return result;
    }


    /**
     * 图片上传
     */
    @PostMapping("/uploadFile")
    public Result<String> uploadFile(@RequestParam(value = "file") MultipartFile file) {

        if (file.isEmpty())
            return Result.error("请选择一个文件");

        Result<String> result;
        try {
            // 转换为上传文件的实体
            UploadFile uploadFile = mongoDbService.getUploadFileEntity(file);
            // 通过 mongoTemplate 保存后，会把数据库自动生成的主键赋值到这个对象上
            UploadFile savedFile = mongoDbService.uploadFile(uploadFile);
            // 构造好这个图片的请求地址返回给前端，我们后面实现这个请求
//            String url = "http://localhost:8080/file/image/" + savedFile.getId();
            String url = mongodbConfig.publicHost + MongodbConfig.PDF + savedFile.getId();
            result = Result.success(url);
        } catch (IOException e) {
            log.error("图片上传失败", e);
            result = Result.error("图片上传失败");
        }
        return result;
    }


    // TODO 将图片接口修改为对公和对私

    /**
     * 获取图片
     */
    @GetMapping(value = "/image/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public byte[] image(@PathVariable("id") String id) {
        byte[] data = null;
        UploadImage file = mongoTemplate.findById(id, UploadImage.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        return data;
    }

    /**
     * 获取二进制的文档资源
     */
    @GetMapping(value = "/pdf_binary/{id}", produces = {MediaType.APPLICATION_PDF_VALUE})
    public byte[] documentFile(@PathVariable("id") String id) {
        byte[] data = null;
        UploadFile file = mongoTemplate.findById(id, UploadFile.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        return data;
    }

    /**
     * 获取文档资源
     */
    @GetMapping(value = "/pdf/{id}", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<Resource> downloadDocumentFile(@PathVariable("id") String id) {
        UploadFile file = mongoTemplate.findById(id, UploadFile.class);
        if (file == null || file.getContent() == null || file.getContent().getData() == null) {
            return ResponseEntity.notFound().build();
        }

        byte[] data = file.getContent().getData();
        String filename = file.getName(); // 假设UploadFile类中有getFilename()方法获取文件名
        // 针对浏览器的特点，将文件名称的编码进行重编码
        try {
            filename = new String(filename.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        // 响应一个文件
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_PDF)
                .body(new ByteArrayResource(data));
    }
}
